<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>

<script type="text/javascript">
    document.body.innerHTML="<div id=div1>aaa</div><div id=div2>bbb</div><div id=div3>ccc</div>";
    for(var i=0;i<4;i++){
        !function(i){
            document.getElementById('div' + i).addEventListener('click',function(){
                alert(i);
            });
        }(i);
    }
</script>
</body>
</html>